﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace TextTransform {
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window {
		const string _postBeginsWith = "<div class='post-body";
		const string _postEndsWith = "<div class='post-footer'>";
		const string _paragraphTab = "[color=#404040]∙ ∙ ∙ ∙ [/color]";
		const string _paragraphSpace = "[color=#404040][size=1]\r\n∙[/size][/color]";
		const string _blogUrl = "my.idaho-adventure.com";
		const string _mapDiv = "<div class=\"map\">";
		const string _urlPattern = "^http://";

		//[size=1]\r\n∙[/size]
		// pattern
		// http://farm5.static.flickr.com/4078/4744758468_355dc817e0_s.jpg
		// http://farm\d\.static\.flickr\.com/\d{4}/\d{10}_[0-9a-f]{10}_s\.jpg
		// substitution
		// <div class="photo"><img src="{match}" alt=""/></div>\n<p>x</p>\n

		public MainWindow() {
			InitializeComponent();
			cbxUseProxy.IsChecked = Settings.UseProxy;
		}

		/// <summary>
		/// Process the supplied URL
		/// </summary>
		private void btnProcess_Click(object sender, RoutedEventArgs e) {
			this.ClearMessage();

			if (!Regex.IsMatch(txtUrl.Text, _urlPattern)) {
				this.ShowMessage("enter a valid URL to process");
				return;
			}

			Exception ex = null;
			txtContent.Text = Web.Content(txtUrl.Text, out ex);
			if (ex != null) { this.ShowMessage(ex); return; }

			// http://www.rhizohm.net/irhetoric/blog/72/default.aspx
			if (this.txtUrl.Text.Contains("flickr")) {
				if (txtContent.Text.Contains("Keep me signed in")) {
					this.FlickrLogin();
					return;
				}
				this.Extract(txtContent.Text);
			} else {
				this.Transform(txtContent.Text);
			}
		}

		private void FlickrLogin() {
			this.ShowMessage("you must login to Flickr");
			webBrowser.Visibility = System.Windows.Visibility.Visible;
			webBrowser.Source = new Uri(txtUrl.Text);
			webBrowser.Navigated += new NavigatedEventHandler(webBrowser_Navigated);
		}

		private void webBrowser_Navigated(Object sender, NavigationEventArgs e) {
			if (e.Uri.ToString() == txtUrl.Text) {
				webBrowser.Visibility = System.Windows.Visibility.Hidden;
				btnProcess_Click(sender, null);
			}
		}

		/// <summary>
		/// Extract image tags from a Flickr set
		/// </summary>
		private void Extract(string text) {
			var re = new Regex(txtPattern.Text);
			if (re.IsMatch(text)) {
				var output = new StringBuilder();
				var format = txtSubstitution.Text
					.Replace("{match}", "{0}")
					.Replace("\\n", Environment.NewLine);
				var match = re.Match(text);

				while (match.Success) {
					output.AppendFormat(format, match.Value.Replace("_s.jpg", "_b.jpg"));
					match = match.NextMatch();
				}
				this.SaveResult(output.ToString());
			} else {
				this.ShowMessage("pattern was not found in source text");
			}
		}

		

		private void btnExit_Click(object sender, RoutedEventArgs e) {
			Application.Current.Shutdown();
		}

		private void SaveResult(string text) {
			txtContent.Text = text;
			Clipboard.SetData(DataFormats.Text, txtContent.Text);
			this.ShowMessage("results have been copied to the clipboard");
		}

		private void ShowMessage(string message) {
			txtMessage.Text = message;
			txtMessage.Visibility = System.Windows.Visibility.Visible;
		}
		private void ShowMessage(System.Exception e) {
			this.ShowMessage(e.Message);
		}

		private void ClearMessage() {
			if (txtMessage != null) {
				txtMessage.Text = string.Empty;
				txtMessage.Visibility = System.Windows.Visibility.Hidden;
			}
		}

		private bool ValidateSettings() {
			if (string.IsNullOrEmpty(txtPattern.Text)) { return false; }
			if (string.IsNullOrEmpty(txtSubstitution.Text)) { return false; }
			return true;
		}

		#region Text Events

		private void txtPattern_TextChanged(object sender, TextChangedEventArgs e) {
			this.ClearMessage();
		}

		private void txtSubstitution_TextChanged(object sender, TextChangedEventArgs e) {
			this.ClearMessage();
		}

		private void txtUrl_TextChanged(object sender, TextChangedEventArgs e) {
			this.ClearMessage();
			txtSubstitution.IsEnabled = txtPattern.IsEnabled = txtUrl.Text.Contains("flickr");
		}

		private void cbxUseProxy_Checked(object sender, RoutedEventArgs e) {
			Settings.UseProxy = cbxUseProxy.IsChecked.Value;
		}

		#endregion



	}
}
